#import "AtAuthPlugin.h"
#import <Flutter/Flutter.h>
#if __has_include(<ATAuthSDK_D/ATAuthSDK.h>)
#import <ATAuthSDK_D/ATAuthSDK.h>
#else
@import ATAuthSDK;
#endif




@interface AtAuthPlugin () <FlutterStreamHandler>
@property (nonatomic, copy) FlutterEventSink eventSink;
@property (nonatomic, weak) UIViewController *topViewController;
@end

@implementation AtAuthPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* methodChannel =
        [FlutterMethodChannel methodChannelWithName:@"at_auth_plugin/method"
                                    binaryMessenger:[registrar messenger]];
    FlutterEventChannel* eventChannel =
        [FlutterEventChannel eventChannelWithName:@"at_auth_plugin/event"
                                  binaryMessenger:[registrar messenger]];

    AtAuthPlugin* instance = [[AtAuthPlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:methodChannel];
    [eventChannel setStreamHandler:instance];
}

#pragma mark - FlutterStreamHandler

- (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events {
    self.eventSink = events;
    return nil;
}

- (FlutterError *)onCancelWithArguments:(id)arguments {
    self.eventSink = nil;
    return nil;
}

#pragma mark - MethodChannel 接口

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    if ([@"setAuthSDKInfo" isEqualToString:call.method]) {
        [self handleSetAuthSDKInfo:call result:result];
    } else if ([@"getLoginToken" isEqualToString:call.method]) {
        [self handleGetLoginToken:result];
    } else if ([@"getSDKVersion" isEqualToString:call.method]) {
        [self handleGetVersion:result];
    } else {
        result(FlutterMethodNotImplemented);
    }
}

#pragma mark - SDK 初始化

- (void)handleSetAuthSDKInfo:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSString *appSecret = call.arguments[@"appSecret"];
    if (!appSecret || [appSecret length] == 0) {
        result([FlutterError errorWithCode:@"INVALID_ARGUMENT"
                                   message:@"appSecret 不能为空"
                                   details:nil]);
        return;
    }

    [[TXCommonHandler sharedInstance] setAuthSDKInfo:appSecret complete:^(NSDictionary * _Nonnull resultDic) {
        result(resultDic);
    }];
}

#pragma mark - 获取登录 Token

- (void)handleGetLoginToken:(FlutterResult)result {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController *presentVC = [self topViewController];
        if (!presentVC) {
            if (self.eventSink) {
                self.eventSink(@{@"resultCode": @"-1", @"msg": @"找不到顶层控制器"});
            }
            return;
        }

        TXCustomModel *model = [self createCustomModel];
        [[TXCommonHandler sharedInstance] getLoginTokenWithTimeout:5.0
                                                       controller:presentVC
                                                           model:model
                                                        complete:^(NSDictionary *dict) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *resultCode = [dict objectForKey:@"resultCode"];
                if ([PNSCodeLoginControllerPresentSuccess isEqualToString:resultCode]) {
                    NSLog(@"授权页拉起成功回调：%@", dict);
                } else if ([PNSCodeLoginControllerClickCancel isEqualToString:resultCode] ||
                           [PNSCodeLoginControllerClickChangeBtn isEqualToString:resultCode] ||
                           [PNSCodeLoginControllerClickLoginBtn isEqualToString:resultCode] ||
                           [PNSCodeLoginControllerClickCheckBoxBtn isEqualToString:resultCode] ||
                           [PNSCodeLoginClickPrivacyAlertView isEqualToString:resultCode] ||
                           [PNSCodeLoginPrivacyAlertViewClickContinue isEqualToString:resultCode] ||
                           [PNSCodeLoginPrivacyAlertViewClose isEqualToString:resultCode]) {
                        NSLog(@"页面点击事件回调：%@", dict);
                }else if([PNSCodeLoginControllerClickProtocol isEqualToString:resultCode] ||
                         [PNSCodeLoginPrivacyAlertViewPrivacyContentClick isEqualToString:resultCode]){
                        NSLog(@"页面点击事件回调：%@", dict);
                
                } else if ([PNSCodeLoginControllerSuspendDisMissVC isEqualToString:resultCode]) {
                    NSLog(@"页面点击事件回调：%@", dict);
                    [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:nil];
                } else if ([@"700020" isEqualToString:resultCode]) {
                    NSLog(@"页面已完全销毁dealloc:%@", dict);
                } else if ([PNSCodeSuccess isEqualToString:resultCode]) {
                    [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:nil];
                } else {
                    NSLog(@"获取LoginToken或拉起授权页失败回调：%@", dict);
                    [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:nil];
                }
                if (self.eventSink) {
                    self.eventSink(dict);
                }
            });
        }];
    });
}

- (void)handleGetVersion:(FlutterResult)result {
    NSString *version = [[TXCommonHandler sharedInstance] getVersion];
    result(version ?: @"unknown");
}

#pragma mark - Custom Model

- (TXCustomModel *)createCustomModel {
    TXCustomModel *model = [[TXCustomModel alloc] init];
    
    NSBundle *bundle = [NSBundle bundleForClass:[AtAuthPlugin class]];
    
    NSString *navPath = [bundle pathForResource:@"icon_nav_back_gray" ofType:@"png"];
    NSString *loginLogoPath = [bundle pathForResource:@"login_logo" ofType:@"png"];
    UIImage *imageNav = [UIImage imageWithContentsOfFile:navPath];
    UIImage *imagesLoginLogo = [UIImage imageWithContentsOfFile:loginLogoPath];
    model.privacyNavBackImage = imageNav;
    // 屏幕方向
    model.supportedInterfaceOrientations = UIInterfaceOrientationMaskPortrait;
    model.suspendDisMissVC = NO;

    model.navColor = UIColor.whiteColor;
    model.navTitle = [[NSAttributedString alloc] init];
//    model.navBackImage = imageNav;
    model.backgroundColor = UIColor.whiteColor;
    
    // logo
    model.logoImage = imagesLoginLogo;
    model.logoFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        if (screenSize.height > screenSize.width) {
            CGFloat width = 195.0;
            CGFloat height = 58.0;
            CGFloat x = superViewSize.width / 2.0 - width / 2.0;
            CGFloat y = 44.0;
            return CGRectMake(x, y, width, height);
        }
        return CGRectZero;
    };
    
    // slogan
    NSDictionary *sloganAttr = @{
        NSForegroundColorAttributeName: [[UIColor blackColor] colorWithAlphaComponent:0.4],
        NSFontAttributeName: [UIFont systemFontOfSize:14]
    };
    NSString *sloganStr = @"中国电信提供认证服务";
    model.sloganText = [[NSAttributedString alloc] initWithString:sloganStr attributes:sloganAttr];
    model.sloganFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        if (screenSize.height > screenSize.width) {
            CGFloat width = frame.size.width;
            CGFloat height = 22.0;
            CGFloat x = superViewSize.width / 2.0 - width / 2.0;
            CGFloat y = 198.0;
            return CGRectMake(x, y, width, height);
        }
        return CGRectZero;
    };
    
    // 手机号
    model.numberColor = [[UIColor blackColor] colorWithAlphaComponent:0.9];
    model.numberFont = [UIFont systemFontOfSize:24];
    model.numberFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        if (screenSize.height > screenSize.width) {
            CGFloat width = frame.size.width;
            CGFloat height = 32.0;
            CGFloat x = superViewSize.width / 2.0 - width / 2.0;
            CGFloat y = 158.0;
            return CGRectMake(x, y, width, height);
        }
        return CGRectZero;
    };
    
    // 一键登录按钮
    NSDictionary *btnAttr = @{
        NSForegroundColorAttributeName: UIColor.whiteColor,
        NSFontAttributeName: [UIFont systemFontOfSize:16]
    };
    NSString *loginBtnStr = @"本机号码一键登录";
    model.loginBtnText = [[NSAttributedString alloc] initWithString:loginBtnStr attributes:btnAttr];
    
    NSString *loginPath = [bundle pathForResource:@"login_btn" ofType:@"png"];
    NSString *dis_loginPath = [bundle pathForResource:@"login_btn_disable" ofType:@"png"];
    
    UIImage *imageLogin = [UIImage imageWithContentsOfFile:loginPath];
    UIImage *imagedis = [UIImage imageWithContentsOfFile:dis_loginPath];
    
    if (imageLogin && imagedis) {
        model.loginBtnBgImgs = @[imageLogin, imagedis, imageLogin];
    }
    
    model.autoHideLoginLoading = NO;
    model.loginBtnFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        if (screenSize.height > screenSize.width) {
            CGFloat width = superViewSize.width - 48.0;
            CGFloat height = 48.0;
            CGFloat x = superViewSize.width / 2.0 - width / 2.0;
            CGFloat y = 244.0;
            return CGRectMake(x, y, width, height);
        }
        return CGRectZero;
    };
    
    // 更多登录方式
    model.changeBtnIsHidden = YES;
    NSDictionary *moreAttr = @{
        NSForegroundColorAttributeName: [[UIColor blackColor] colorWithAlphaComponent:0.6],
        NSFontAttributeName: [UIFont systemFontOfSize:16]
    };
    NSString *loginMoreStr = @"更多登录方式";
    UIButton *moreBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [moreBtn setTitle:loginMoreStr forState:UIControlStateNormal];
    [moreBtn setTitleColor:[[UIColor blackColor] colorWithAlphaComponent:0.6] forState:UIControlStateNormal];
    [moreBtn setAttributedTitle:[[NSAttributedString alloc] initWithString:loginMoreStr attributes:moreAttr]
                       forState:UIControlStateNormal];
    [moreBtn addTarget:self action:@selector(_moreTypeLoginClick) forControlEvents:UIControlEventTouchUpInside];
    
    model.customViewBlock = ^(UIView *superCustomView) {
        [superCustomView addSubview:moreBtn];
    };
    

    
    model.customViewLayoutBlock = ^(CGSize screenSize, CGRect contentViewFrame, CGRect navFrame, CGRect titleBarFrame, CGRect logoFrame, CGRect sloganFrame, CGRect numberFrame, CGRect loginFrame, CGRect changeBtnFrame, CGRect privacyFrame) {
        
        moreBtn.frame = CGRectMake(CGRectGetMinX(loginFrame),
                                   CGRectGetMaxY(loginFrame) + 20.0,
                                   CGRectGetWidth(loginFrame),
                                   30.0);
    };


    NSString *path = [bundle pathForResource:@"check_box" ofType:@"png"];
    NSString *sel_path = [bundle pathForResource:@"check_box_sel" ofType:@"png"];
    
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    UIImage *imagesel = [UIImage imageWithContentsOfFile:sel_path];

    model.checkBoxImages = @[
       image, imagesel
    ];

    NSString *privacyOneStr = @"《用户协议》";
    model.privacyOne = @[privacyOneStr, @"https://casdon-privacy.casdon.com.cn/agreement.html"];
    model.privacyOneColor = [self colorWithHexString:@"#6758D4"];
    
    NSString *privacyTwoStr = @"《隐私政策》";
    model.privacyTwo = @[privacyTwoStr, @"https://oss-cloud.casdon.com.cn/policy/privacy.html?v=121121121"];
    model.privacyTwoColor = [self colorWithHexString:@"#6758D4"];
    
    model.privacyOperatorColor = [self colorWithHexString:@"#6758D4"];
    
    return model;
}

- (UIColor *)colorWithHexString:(NSString *)hex {
    unsigned int rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hex];
    [scanner setScanLocation:1]; // 跳过 #
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue >> 16) & 0xFF) / 255.0
                           green:((rgbValue >> 8) & 0xFF) / 255.0
                            blue:(rgbValue & 0xFF) / 255.0
                           alpha:1.0];
}


#pragma mark - 资源加载

- (UIImage *)imageNamed:(NSString *)name fromBundleNamed:(NSString *)bundleName {
    NSBundle *bundle = [self bundleWithName:bundleName];
    UIImage *image = [UIImage imageNamed:name inBundle:bundle compatibleWithTraitCollection:nil];
    return image;
}

- (NSBundle *)bundleWithName:(NSString *)bundleName {
    NSBundle *mainBundle = [NSBundle bundleForClass:[self class]];
    NSURL *bundleURL = [mainBundle URLForResource:bundleName withExtension:@"bundle"];
    return [NSBundle bundleWithURL:bundleURL];
}

#pragma mark - 其他方式登录

- (void)_moreTypeLoginClick {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController *vc = [self topViewController];
        if (vc.presentedViewController) {
            [vc dismissViewControllerAnimated:YES completion:nil];
        } else if (vc.presentingViewController) {
            [vc.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        }
        if (self.eventSink) {
            self.eventSink(@{@"type": @"otherLogin"});
        }
    });
}

#pragma mark - 顶层控制器

- (UIViewController *)topViewController {
    UIViewController *rootVC = [UIApplication sharedApplication].delegate.window.rootViewController;
    return [self topViewControllerFrom:rootVC];
}

- (UIViewController *)topViewControllerFrom:(UIViewController *)vc {
    if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self topViewControllerFrom:((UITabBarController *)vc).selectedViewController];
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self topViewControllerFrom:((UINavigationController *)vc).visibleViewController];
    } else if (vc.presentedViewController) {
        return [self topViewControllerFrom:vc.presentedViewController];
    } else {
        return vc;
    }
}

@end

